<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Configuration</title>
</head>

<body>

<h2>Configuration</h2>

<p>JBehave was designed to be highly embeddable in its
configuration and execution. At its heart, we have the <a
	href="javadoc/core/org/jbehave/core/Embeddable.html">Embeddable</a>
interface, which can specify the <a
	href="javadoc/core/org/jbehave/core/embedder/Embedder.html">Embedder</a>
to use for the running of the stories.</p>

<p>The Embedder separates the concerns of the configuration of the
story execution from the matching of the textual story steps to Java
methods:</p>
<ul>
	<li><a
		href="javadoc/core/org/jbehave/core/configuration/Configuration.html">Configuration</a>
	instances are responsible for the configuration of story execution.</li>
	<li><a
		href="javadoc/core/org/jbehave/core/steps/CandidateSteps.html">CandidateSteps</a>
	instances are used to find the Java methods that match the textual
	steps in the stories.</li>
</ul>
<p>The Embedder needs both the Configuration and the list of
CandidateSteps. Although it has sensible defaults for the configuration
(such as <a
	href="javadoc/core/org/jbehave/core/configuration/MostUsefulConfiguration.html">MostUsefulConfiguration</a>)
we need, for any significant story running, to configure at least one
steps instance.</p>

<span class="followup">JBehave allows multiple paths to the
configuration of the Embedder, so that users can choose the one that
best fits their need.</span>

<h3>Using AnnotatedEmbedder</h3>

<p>JBehave supports the ability to specify configuration elements
and steps instance via annotations. An example of annotated
configuration of the Embedded via annotations is:</p>

<script type="syntaxhighlighter" class="brush: java">
<![CDATA[
@RunWith(AnnotatedEmbedderRunner.class)
@Configure(storyControls = MyStoryControls.class, storyLoader = MyStoryLoader.class, storyReporterBuilder = MyReportBuilder.class, 
        parameterConverters = { MyDateConverter.class })
@UsingEmbedder(embedder = Embedder.class, generateViewAfterStories = true, ignoreFailureInStories = true, ignoreFailureInView = true, verboseFailures = true,
                storyTimeoutInSecs = 100, threads = 2, metaFilters = "-skip")
@UsingSteps(instances = { TraderSteps.class, BeforeAfterSteps.class, AndSteps.class, CalendarSteps.class,
        PriorityMatchingSteps.class, SandpitSteps.class, SearchSteps.class })
public class AnnotatedTraderEmbedder extends InjectableEmbedder {

    @Test
    public void run() {
        List<String> storyPaths = new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), "**/*.story", "");
        injectedEmbedder().runStoriesAsPaths(storyPaths);
    }

    public static class MyStoryControls extends StoryControls {
        public MyStoryControls() {
            doDryRun(false);
            doSkipScenariosAfterFailure(false);
        }
    }

    public static class MyStoryLoader extends LoadFromClasspath {
        public MyStoryLoader() {
            super(AnnotatedTraderEmbedder.class.getClassLoader());
        }
    }

    public static class MyReportBuilder extends StoryReporterBuilder {
        public MyReportBuilder() {
            this.withFormats(CONSOLE, TXT, HTML, XML).withDefaultFormats();
        }
    }

    public static class MyRegexPrefixCapturingPatternParser extends RegexPrefixCapturingPatternParser {
        public MyRegexPrefixCapturingPatternParser() {
            super("%");
        }
    }

    public static class MyDateConverter extends DateConverter {
        public MyDateConverter() {
            super(new SimpleDateFormat("yyyy-MM-dd"));
        }
    }

}
]]>
</script>

<p>Here we are actually using a JUnit Runner, <a
	href="javadoc/core/org/jbehave/core/junit/AnnotatedEmbedderRunner.html">AnnotatedEmbedderRunner</a>,
to bootstrap the configuration process. The AnnotatedEmbedderRunner is a very
thin wrapper around the <a
	href="javadoc/core/org/jbehave/core/configuration/AnnotationBuilder.html">AnnotationBuilder</a>,
building the Embedder and injecting in the test class, which extends <a
	href="javadoc/core/org/jbehave/core/InjectableEmbedder.html">InjectableEmbedder</a>.
</p>

<span class="followup">Note that JBehave follows a
configuration-by-convention approach, by which a default value of the
configuration element is always provided but can be overridden, when
needed.</span>

<h3>Using AnnotationBuilder</h3>

<p>If we wanted to use the AnnotationBuilder directly, the above
example would become:</p>
<script type="syntaxhighlighter" class="brush: java">
<![CDATA[
@Configure(storyLoader = MyStoryLoader.class, storyReporterBuilder = MyReportBuilder.class, 
        parameterConverters = { MyDateConverter.class })
@UsingEmbedder(embedder = Embedder.class, generateViewAfterStories = true, ignoreFailureInStories = true, ignoreFailureInView = true, verboseFailures = true,
                storyTimeoutInSecs = 100, threads = 2, metaFilters = "-skip")
@UsingSteps(instances = { TraderSteps.class, BeforeAfterSteps.class, AndSteps.class, CalendarSteps.class,
        PriorityMatchingSteps.class, SandpitSteps.class })
public class TraderAnnotatedEmbedder {

    private Embedder embedder;
    
    public TraderAnnotatedEmbedder(){
        embedder = new AnnotationBuilder(this).buildEmbedder();
    }
    
    @Test
    public void run() {
        embedder.runStoriesAsPaths(new StoryFinder().findPaths(codeLocationFromClass(this.getClass()).getFile(),
                asList("**/*.story"), asList("")));
    }

    public static class MyReportBuilder extends StoryReporterBuilder {
        public MyReportBuilder() {
            this.withFormats(CONSOLE, TXT, HTML, XML).withDefaultFormats();
        }
    }

    public static class MyStoryLoader extends LoadFromClasspath {
        public MyStoryLoader() {
            super(TraderAnnotatedEmbedder.class.getClassLoader());
        }
    }

    public static class MyRegexPrefixCapturingPatternParser extends RegexPrefixCapturingPatternParser {
        public MyRegexPrefixCapturingPatternParser() {
            super("%");
        }
    }

    public static class MyDateConverter extends DateConverter {
        public MyDateConverter() {
            super(new SimpleDateFormat("yyyy-MM-dd"));
        }
    }

}
]]>
</script>

<span class="followup"> The <a
	href="javadoc/core/org/jbehave/core/configuration/AnnotationBuilder.html">AnnotationBuilder</a>
requires that configuration elements and the steps instances provide a
default constructor. This limitation is overcome by using <a
	href="dependency-injection.html">dependency injection</a> containers.
Note that the use of dependency injection annotations overrides the one
specified by the <b>@Configure</b> and <b>@UsingSteps</b>.</span>

<h3>Using ConfigurableEmbedder</h3>

<p>A <a
	href="javadoc/core/org/jbehave/core/ConfigurableEmbedder.html">ConfigurableEmbedder</a>
is an abstract implementation of <a
	href="javadoc/core/org/jbehave/core/Embeddable.html">Embeddable</a>,
which allows subclasses to specify the Configuration and CandidateSteps
directly. A notable subclass of ConfigurableEmbedder is <a
	href="javadoc/core/org/jbehave/core/junit/JUnitStory.html">JUnitStory</a>,
which allows each subclass to be run as a separate individual story.</p>

<p>Even if each JUnitStory Java class can be configured
independently, it is good practice to collect the configuration that
applies to all stories in an abstract (i.e. not runnable) base class:</p>
<script type="syntaxhighlighter" class="brush: java">
<![CDATA[
public abstract class TraderStory extends JUnitStory {

    private final CrossReference xref = new CrossReference();

    public TraderStory() {
        configuredEmbedder().embedderControls().doGenerateViewAfterStories(true).doIgnoreFailureInStories(true)
                .doIgnoreFailureInView(true).useThreads(2).useStoryTimeoutInSecs(60);
        // Uncomment to set meta filter, which can also be set via Ant or Maven
        // configuredEmbedder().useMetaFilters(Arrays.asList("+theme parametrisation"));
    }

    @Override
    public Configuration configuration() {
        Class<? extends Embeddable> embeddableClass = this.getClass();
        Properties viewResources = new Properties();
        viewResources.put("decorateNonHtml", "true");
        // Start from default ParameterConverters instance
        ParameterConverters parameterConverters = new ParameterConverters();
        // factory to allow parameter conversion and loading from external
        // resources (used by StoryParser too)
        ExamplesTableFactory examplesTableFactory = new ExamplesTableFactory(new LocalizedKeywords(),
                new LoadFromClasspath(embeddableClass), parameterConverters);
        // add custom converters
        parameterConverters.addConverters(new DateConverter(new SimpleDateFormat("yyyy-MM-dd")),
                new ExamplesTableConverter(examplesTableFactory));

        return new MostUsefulConfiguration()
                .useStoryControls(new StoryControls().doDryRun(false).doSkipScenariosAfterFailure(false))
                .useStoryLoader(new LoadFromClasspath(embeddableClass))
                .useStoryParser(new RegexStoryParser(examplesTableFactory))
                .useStoryPathResolver(new UnderscoredCamelCaseResolver())
                .useStoryReporterBuilder(
                        new StoryReporterBuilder()
                                .withCodeLocation(CodeLocations.codeLocationFromClass(embeddableClass))
                                .withDefaultFormats().withPathResolver(new ResolveToPackagedName())
                                .withViewResources(viewResources).withFormats(CONSOLE, TXT, HTML, XML)
                                .withFailureTrace(true).withFailureTraceCompression(true).withCrossReference(xref))
                .useParameterConverters(parameterConverters)
                // use '%' instead of '$' to identify parameters
                .useStepPatternParser(new RegexPrefixCapturingPatternParser("%")) 
                .useStepMonitor(xref.getStepMonitor());
    }

    @Override
    public InjectableStepsFactory stepsFactory() {
        return new InstanceStepsFactory(configuration(), new TraderSteps(new TradingService()), new AndSteps(), new MetaParametrisationSteps(),
                new CalendarSteps(), new PriorityMatchingSteps(), new PendingSteps(), new ParametrisedSteps(), new SandpitSteps(),
                new SearchSteps(), new BeforeAfterSteps(), new CompositeSteps(), new CompositeNestedSteps(), new NamedParametersSteps());
    }

}  
]]>
</script>

<p>Once we have a configured instance of ConfigurableEmbedder, all
we need to do is to extend it providing the name of the executable Story
class that maps to the textual story file. For example, to map to <b>trader_is_alerted_of_status.story</b>
using the resolver defined above:</p>
<pre class="brush: java">
public class TraderIsAlertedOfStatus extends TraderStory {

}
</pre>

<p>To run multiple stories, specified as story paths, one can use
another subclass of ConfigurableEmbdder, <a
	href="javadoc/core/org/jbehave/core/junit/JUnitStories.html">JUnitStories</a>:
</p>

<script type="syntaxhighlighter" class="brush: java">
<![CDATA[
public class TraderStories extends JUnitStories {

    public TraderStories() {
        // configure as TraderStory except for 
        Configuration configuration = new MostUsefulConfiguration()
                .useStoryLoader(new LoadFromURL())
    }

	@Override
	protected List<String> storyPaths() {
        String codeLocation = codeLocationFromClass(this.getClass()).getFile();
        return new StoryFinder().findPaths(codeLocation, asList("**/trader*.story"),
                    asList(""), "file:"+codeLocation);
	}
]]>
</script>

<span class="followup">Note that in this second example, we are
using story paths as URLs, and correspondingly we configure the use of <a
	href="javadoc/core/org/jbehave/core/io/LoadFromURL.html">LoadFromURL</a>.</span>

<h3>Scanning for steps</h3>

<p>JBehave also supports the ability to scan packages for the Steps classes.  If using the annotated approach:</p>

<script type="syntaxhighlighter" class="brush: java">
<![CDATA[
@UsingSteps(packages = { "org.jbehave.examples.core.steps", "my.other.steps" }, matchingNames = ".*Steps", notMatchingNames = ".*SkipSteps" )
]]>
</script>

<p>If using the programmatic approach:</p>

<script type="syntaxhighlighter" class="brush: java">
<![CDATA[
    public InjectableStepsFactory stepsFactory() {
        return new ScanningStepsFactory(configuration(), "org.jbehave.examples.core.steps", "my.other.steps" ).matchingNames(".*Steps").notMatchingNames(".*SkipSteps");
    }
]]>
</script>

<p>Scanning requires an additional runtime dependency on <a href="https://github.com/ronmamo/reflections">Reflections</a>:</p>

<script type="syntaxhighlighter" class="brush: xml">
<![CDATA[
    <dependency>
        <groupId>org.reflections</groupId>
        <artifactId>reflections</artifactId>
        <version>[version]</version>
    </dependency>
]]>
</script>

<span class="followup">It is important to remember that all Steps classes created using the scanning approach must have a default constructor and no 
<a href="dependency-injection.html">dependency injection</a> mechanism is supported.  If dependency injection is required, most frameworks also support
their own version of class scanning.</span>

<h3>Configurable Elements</h3>

<p>All configurable elements of <a
	href="javadoc/core/org/jbehave/core/Configuration.html">Configuration</a>
come with a default behaviour, configured in the <a
	href="javadoc/core/org/jbehave/core/MostUsefulConfiguration.html">MostUsefulConfiguration</a>:</p>
<ul>
	<li><a
		href="javadoc/core/org/jbehave/core/configuration/Keywords.html">Keywords</a>:
	defaults to <a
		href="javadoc/core/org/jbehave/core/i18n/LocalizedKeywords.html">LocalizedKeywords</a>.</li>
	<li><a
		href="javadoc/core/org/jbehave/core/failures/FailureStrategy.html">FailureStrategy</a>:
	Allows to define the strategy for error handling. The default value is
	<a
		href="javadoc/core/org/jbehave/core/failures/RethrowingFailureStrategy.html">RethrowingFailureStrategy</a>.</li>
	<li><a
		href="javadoc/core/org/jbehave/core/steps/StepCollector.html">StepCollector</a>:
	Represents the strategy for the collection of executable steps from a
	given story matching a list of candidate steps. The default
	implementation is <a
		href="javadoc/core/org/jbehave/core/steps/MarkUnmatchedStepsAsPending.html">MarkUnmatchedStepsAsPending</a>.</li>
	<li><a
		href="javadoc/core/org/jbehave/core/embedder/StoryControls.html">StoryControls</a>:
	Controls the story execution workflow.</li>
	<li><a href="javadoc/core/org/jbehave/core/io/StoryParser.html">StoryParser</a>:
	Parses stories contained in a textual story file. The default
	implementation is <a
		href="javadoc/core/org/jbehave/core/io/RegexStoryParser.html">RegexStoryParser</a>.</li>
	<li><a
		href="javadoc/core/org/jbehave/core/parsers/StepPatternParser.html">StepPatternParser</a>:
	defaults to <a
		href="javadoc/core/org/jbehave/core/parsers/RegexPrefixCapturingPatternBuilder.html">RegexPrefixCapturingPatternParser</a>.
	</li>
	<li><a href="javadoc/core/org/jbehave/core/steps/StepMonitor.html">StepMonitor</a>:
	defaults to <a
		href="javadoc/core/org/jbehave/core/steps/SilentStepMonitor.html">SilentStepMonitor</a>,
	useful to either debug the step matching or to describe the steps being
	performed to some output.</li>
	<li>The <a
		href="javadoc/core/org/jbehave/core/reporters/StoryReporterBuilder.html">StoryReporterBuilder</a>:
	facade for building instances of <a
		href="javadoc/core/org/jbehave/core/reporters/StoryReporter.html">StoryReporter</a>.
	The <a
		href="javadoc/core/org/jbehave/core/reporters/ViewGenerator.html">ViewGenerator</a>
	allows to generate view of reports run. The default implementation is <a
		href="javadoc/core/org/jbehave/core/reporters/FreemarkerViewGenerator.html">FreemarkerViewGenerator</a>.</li>
	<li><a
		href="javadoc/core/org/jbehave/core/steps/ParameterConverters.html">ParameterConverters</a>:
	facade for collecting user-defined implementations of <a
		href="javadoc/core/org/jbehave/core/steps/ParameterConverters.ParameterConverter.html">ParameterConverter</a>.</li>
</ul>

<h3>Controlling the Embedder using Maven or Ant</h3>

<p>All the elements of <a
    href="javadoc/core/org/jbehave/core/embedder/EmbedderControls.html">EmbedderControls</a> are also configurable via <a href="maven-goals.html">Maven goals</a> or <a href="ant-tasks.html">Ant tasks</a>.</p>

<span class="followup">It is important to note that JBehave adopts an <b>out-in approach</b> to configuration.  Any inner-layer configuration, such as specified in the code,
 will be overridden by the outer-layer configuration, such as specified by the command-line tools like Maven or Ant.</span>

<div class="clear">
<hr />
</div>

</body>
</html>
